package com.mzy.concurrent;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: mizy3
 * @Date: 2024/09/08/下午3:48
 * @Description:
 */
public class 三线程打印1到100 {
    public volatile static int state = 0;
    public final static Object lock = new Object();
    public static int i = 1;

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (lock) {

                while (i <= 100) {
                    while (state != 1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        if (i > 100) break;

                    }
                    if (i > 100) break;

                    System.out.println(Thread.currentThread().getName() + " " + i++);
                    state = 2;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(() -> {
            synchronized (lock) {
                while (i <= 100) {
                    while (state != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        if (i >100) break;
                    }
                    if (i >100) break;

                    System.out.println(Thread.currentThread().getName() + " " + i++);
                    state = 1;
                    lock.notifyAll();
                }
            }
        }).start();


        new Thread(() -> {
            synchronized (lock) {
                while (i <= 100) {
                    while (state != 2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        if (i > 100) break;
                    }
                    if (i > 100) break;

                    System.out.println(Thread.currentThread().getName() + " " + i++);
                    state = 0;
                    lock.notifyAll();
                }
            }
        }).start();

    }
}
